﻿using System.Drawing;
using System.IO;

namespace WebPages.Bll
{
    public class GraphicUtilities
    {
        const int DEFAULT_THUMBNAIL_PIXEL_WIDTH = 64;
        const int DEFAULT_THUMBNAIL_PIXEL_HEIGHT = 64;

        /// <summary>
        /// Creates a thumbnail image using the default thumbnail size. Image aspect ratio is respected
        /// </summary>
        /// <param name="sourceImage">Source image</param>
        /// <returns>The thumbnail image</returns>
        public Stream CreateThumbnail(Stream sourceImage)
        {
            return ResizeImage(sourceImage, true, DEFAULT_THUMBNAIL_PIXEL_WIDTH, DEFAULT_THUMBNAIL_PIXEL_HEIGHT);
        }

        /// <summary>
        /// Resizes an image
        /// </summary>
        /// <param name="sourceImage">Source image to process</param>
        /// <param name="keepAspectRatio">If true then image aspect ratio is respected, if false the image may be stretched to fit the given width and height</param>
        /// <param name="maxPixelWidth">New image width</param>
        /// <param name="maxPixelHeight">New image height</param>
        /// <returns>The resized image</returns>
        public Stream ResizeImage(Stream sourceImage, bool keepAspectRatio, int maxPixelWidth, int maxPixelHeight)
        {
            var orig = new Bitmap(sourceImage);
            int width;
            int height;

            if (keepAspectRatio)
            {
                if (orig.Width > orig.Height)
                {
                    width = maxPixelWidth;
                    height = maxPixelWidth * orig.Height / orig.Width;
                }
                else
                {
                    height = maxPixelHeight;
                    width = maxPixelHeight * orig.Width / orig.Height;
                }
            }
            else
            {
                width = maxPixelWidth;
                height = maxPixelHeight;
            }

            var thumbnailImage = new Bitmap(width, height);

            using (var graphic = Graphics.FromImage(thumbnailImage))
            {
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphic.DrawImage(orig, 0, 0, width, height);
                var stream = new MemoryStream();
                thumbnailImage.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Seek(0, SeekOrigin.Begin);
                return stream;
            }
        }
    }
}